package com.yh.listener;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * @Auther: Liang
 * @Date: 2024/5/16 - 05 - 16 - 10:17
 * @Description: com.yh.listener
 * @version: 1.0
 */
//这里是使用监听器实现spring容器与web的集成
//@WebListener
public class MyListener implements ServletContextListener {

    public MyListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //在服务器启动时加载配置文件
        ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
        //存入全局作用域
        sce.getServletContext().setAttribute("spring",applicationContext);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //服务器关闭时 获取全局作用域中的spring容器
        ClassPathXmlApplicationContext spring = (ClassPathXmlApplicationContext) sce.getServletContext().getAttribute("spring");
        spring.close();
    }
}
